// src/hooks/useWebSocket.ts
'use client'

import { useRef, useCallback } from "react";
import { handleNotifyClick, requestNotificationPermission } from "./notification";

// 自定义Hook必须以use开头
export default function useWebSockets() {
    // WebSocket实例的引用
    const webSocketRef = useRef<WebSocket | null>(null);

    // 连接WebSocket
    const connectWebSocket = useCallback((userId: string) => {
        // 关闭现有连接
        if (webSocketRef.current) {
            webSocketRef.current.close();
        }

        // 创建新连接
        const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
        const wsUrl = `${wsProtocol}//localhost:8099/websocket/${userId ? userId : 'user_1'}`;
        webSocketRef.current = new WebSocket(wsUrl);

        // 连接成功
        webSocketRef.current.onopen = () => {
            console.log('WebSocket连接成功');
            requestNotificationPermission();
        };

        // 接收消息
        webSocketRef.current.onmessage = (event: MessageEvent) => {
            console.log('收到消息:', event.data);
            handleNotifyClick(event.data);

            // 简单解析在线人数（实际应用中可能需要更复杂的逻辑）
            const onlineMatch = event.data.match(/当前在线人数为(\d+)/);
            if (onlineMatch && onlineMatch[1]) {
                console.log('在线人数:', onlineMatch[1]);
            }
        };

        // 连接关闭
        webSocketRef.current.onclose = () => {
            console.log('WebSocket连接关闭');
        };

        // 连接错误
        webSocketRef.current.onerror = (error: Event) => {
            console.error('WebSocket错误:', error);
        };
    }, []);

    // 断开连接
    const disconnectWebSocket = useCallback(() => {
        if (webSocketRef.current) {
            webSocketRef.current.close();
            webSocketRef.current = null;
        }
    }, []);

    // 发送消息
    const sendMessage = useCallback((message: string) => {
        if (!webSocketRef.current || webSocketRef.current.readyState !== WebSocket.OPEN || !message.trim()) {
            return;
        }

        webSocketRef.current.send(message.trim());
    }, []);

    return {
        connectWebSocket,
        disconnectWebSocket,
        sendMessage
    };
}